package jpb.test.util;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

import static jpb.Assert.notNull;

/**
 * Utility for creating/cleaning up temporary directories for tests.
 *
 * @author Dariusz Kordonski
 */
public final class DirSetup {

    private final String testDirName;
    private final File testDir;

    public DirSetup(String testDirName) {
        this.testDirName = notNull("testDirName", testDirName);
        this.testDir = new File(System.getProperty("java.io.tmpdir") + File.separator + testDirName);
    }

    public DirSetup setUp() throws IOException {
        tearDown();
        tryCreate();
        return this;
    }

    public DirSetup tearDown() throws IOException {
        if (testDir.exists()) {
            FileUtils.deleteDirectory(testDir);
        }
        return this;
    }

    public File testDir() {
        return testDir;
    }

    public File createFile(String name) throws IOException {
        File answer = new File(testDir, notNull("name", name));
        if (!answer.createNewFile()) {
            throw new IllegalStateException("Could not create file named <" + name + "> in test dir: " + testDir);
        }
        return answer;
    }

    public File createFile(String dirName, String name) throws IOException {
        File dirFile = new File(testDir, notNull("dirName", dirName));
        if (!dirFile.exists()) {
            dirFile = createDir(dirName);
        }
        File answer = new File(dirFile, notNull("name", name));
        if (!answer.createNewFile()) {
            throw new IllegalStateException("Could not create file named <" + name + "> in test dir: "
                    + dirFile.getAbsolutePath());
        }
        return answer;
    }

    public File createDir(String name) {
        File answer = new File(testDir, notNull("name", name));
        if (!answer.mkdir()) {
            throw new IllegalStateException("Could not create directory named <" + name + "> in test dir: " + testDir);
        }
        return answer;
    }

    private void tryCreate() throws IOException {
        if (!testDir.mkdir()) {
            throw new IOException("Could not create test directory [" + testDir.getAbsolutePath() + "]");
        }
    }



}
